iT邦幫忙

2025 iThome 鐵人賽

DAY 7
0
AI & Data

Rosalind 生物資訊解題系統系列 第 7

Day07 | Rosalind 生資解題 - IN6. Dictionaries +defaultdict

  • 分享至 

  • xImage
  •  

Day07 | Rosalind 生資解題 - IN6. Dictionaries +defaultdict

題目連結:https://rosalind.info/problems/ini6/

https://ithelp.ithome.com.tw/upload/images/20250918/20125192WweoYXMCtb.png

計算每個字詞出現的次數,區分大小寫(Python Dict 預設就是大小寫敏感
這題開始有一點點難度了

輸入

We tried list and we tried dicts also we tried Zen

輸出

and 1
We 1
tried 3
dicts 1
list 1
we 2
also 1
Zen 1

解法一

首先將輸入字串,按照空白字元做切割,得到一個陣列

['We', 'tried', 'list', 'and', 'we', 'tried', 'dicts', 'also', 'we', 'tried', 'Zen']

用迴圈叠代跑過一輪
當字典里有目前的字(key),數字(value)就+1。
若字典里還沒有,則創造此字(key),數字(value)為1。

程式碼:

s = "We tried list and we tried dicts also we tried Zen"

counts = dict()
for word in s.split():
    counts[word] = counts.get(word, 0) + 1

for key,value in counts.items():
    print(key, value)

注意最後印出不能直接print(d)
而是要按照插入字典時的順序(所以題目的Hint中有這一段d.items()

解法二

或者使用 defaultdict

from collections import defaultdict

def count_word_occurrences(s):
    counts = defaultdict(int)  # 使用defaultdict來將value初始化為0

    for word in s.split():
        counts[word] += 1

    for word, count in counts.items():
        print(word, count)


s = "We tried list and we tried dicts also we tried Zen"
count_word_occurrences(s)

上一篇
Day06 | Rosalind 生資解題 - IN5. Working with Files +讀檔操作
系列文
Rosalind 生物資訊解題系統7
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言